package com.mygame.gateway.server;

import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import com.google.common.util.concurrent.RateLimiter;
import com.mygame.gateway.common.GatewayServerConfig;
import com.mygame.gateway.server.handler.ConfirmHandler;
import com.mygame.gateway.server.handler.DispatchGameMessageHandler;
import com.mygame.gateway.server.handler.HeartbeatHandler;
import com.mygame.gateway.server.handler.codec.DecodeHandler;
import com.mygame.gateway.server.handler.codec.EncodeHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;

@Service
public class GatewayServerBoot {
	@Autowired
	private GatewayServerConfig serverConfig;// 注入网关服务配置

	private NioEventLoopGroup bossGroup = null;
	private NioEventLoopGroup workerGroup = null;
	private Logger logger = LoggerFactory.getLogger(GatewayServerBoot.class);
	private RateLimiter globalRateLimiter;
	@Autowired
	private ApplicationContext applicationContext;

	public void startServer() {

		globalRateLimiter = RateLimiter.create(serverConfig.getGlobalRequestPerSecond());
		bossGroup = new NioEventLoopGroup(serverConfig.getBossThreadCount());
		// 业务逻辑线程组
		workerGroup = new NioEventLoopGroup(serverConfig.getWorkThreadCount());

		int port = this.serverConfig.getPort();
		try {
			ServerBootstrap b = new ServerBootstrap();
			// 这里遇到一个小问题，如果把childHandler的加入放在option的前面，option将会不生效。我用java socket连接，一直没有消息返回。
			b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 128)
					.childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.TCP_NODELAY, true)
					.childHandler(createChannelInitializer());
			logger.info("开始启动服务，端口:{}", port);
			ChannelFuture f = b.bind(port);
			f.channel().closeFuture().sync();
			logger.info("服务器关闭成功");
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			workerGroup.shutdownGracefully();
			bossGroup.shutdownGracefully();
		}
	}

	private ChannelInitializer<Channel> createChannelInitializer() {// 连接channel初始化的时候调用
		ChannelInitializer<Channel> channelInitializer = new ChannelInitializer<Channel>() {
			@Override
			protected void initChannel(Channel ch) throws Exception {
				ChannelPipeline p = ch.pipeline();
				try {
					int readerIdleTimeSeconds = serverConfig.getReaderIdleTimeSeconds();
					int writerIdleTimeSeconds = serverConfig.getWriterIdleTimeSeconds();
					int allIdleTimeSeconds = serverConfig.getAllIdleTimeSeconds();
					if(serverConfig.isEnableHeartbet()) {
						p.addLast(new IdleStateHandler(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds));
					}
					p.addLast("EncodeHandler", new EncodeHandler());// 添加编码Handler
					p.addLast(new LengthFieldBasedFrameDecoder(1024 * 8, 0, 4, -4, 0));// 添加拆包
					p.addLast("DecodeHandler", new DecodeHandler());// 添加解码
					p.addLast("ConfirmHandler", new ConfirmHandler(applicationContext));
					// 添加限流handler
					//p.addLast("RequestLimit",
					//		new RequestRateLimiterHandler(globalRateLimiter, serverConfig.getRequestPerSecond()));

					
					p.addLast("HeartbeatHandler", new HeartbeatHandler());
					p.addLast(new DispatchGameMessageHandler(applicationContext));
				} catch (Exception e) {
					ch.close();
					logger.error("创建channel失败", e);
				}
			}
		};
		return channelInitializer;
	}

	public void stop() {// 优雅的关闭服务
		int quietPeriod = 5;
		int timeout = 30;
		TimeUnit timeUnit = TimeUnit.SECONDS;
		workerGroup.shutdownGracefully(quietPeriod, timeout, timeUnit);
		bossGroup.shutdownGracefully(quietPeriod, timeout, timeUnit);
	}
}
